require('reflect-metadata');
const { config } = require('dotenv');
const { DataSource } = require('typeorm');

// 加载测试环境变量
config({ path: '.env.test' });

// 直接导入实体类（使用 tsup 构建的入口文件）
const { User, CrawlerTask, CrawledData } = require('@weubi/shared');

async function debugEntities() {
  console.log('🔧 调试实体元数据...');
  
  // 创建测试数据库连接
  const testDataSource = new DataSource({
    type: 'postgres',
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '5433'),
    username: process.env.DB_USER || 'crawler',
    password: process.env.DB_PASSWORD || '123qwe',
    database: process.env.DB_NAME || 'weubi_crawler_test',
    synchronize: true,
    logging: false,
    entities: [User, CrawlerTask, CrawledData],
    dropSchema: false,
  });

  try {
    await testDataSource.initialize();
    console.log('✅ 测试数据库连接成功');
    
    // 检查实体元数据
    console.log('📊 检查实体元数据:');
    const entities = testDataSource.entityMetadatas;
    console.log(`发现 ${entities.length} 个实体:`);
    
    entities.forEach(entity => {
      console.log(`- ${entity.name} (表名: ${entity.tableName})`);
    });
    
    // 尝试获取 User 仓库
    console.log('\n🔍 尝试获取 User 仓库:');
    try {
      const userRepo = testDataSource.getRepository(User);
      console.log('✅ User 仓库获取成功');
      
      // 尝试查询
      const count = await userRepo.count();
      console.log(`📈 User 表中有 ${count} 条记录`);
    } catch (error) {
      console.error('❌ User 仓库获取失败:', error.message);
    }
    
    await testDataSource.destroy();
    console.log('✅ 数据库连接已关闭');
    
  } catch (error) {
    console.error('❌ 调试失败:', error);
  }
}

debugEntities();
